import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_oh_test/pages/sub_web_page.dart';
import 'package:flutter_oh_test/pages/sub_web_page_two.dart';
import 'dart:async';

void main() {
   runApp(const MyApp());
 }

 class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const WebViewPage(),
    );
  }
}


class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key});

  @override
  State<WebViewPage> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {

   late WebViewController controller;
  String message = "init";
  String filePath = 'html/index.html';
   var contextRef;

  @override
  void initState() {
    // 2
    controller = WebViewController();
    controller.setJavaScriptMode(JavaScriptMode.unrestricted);
    controller.loadRequest(Uri.parse("https://m.hnair.com/cms/config/nightly/gdpr/confirm/"));
    //controller.loadFlutterAsset("html/index.html");
    controller.addJavaScriptChannel(
      "JsObj",
      onMessageReceived: (JavaScriptMessage message) => {
        nextSubPage()
        /*setState(() {
          this.message = message.message;
          //接收到js返回的数据
          //收到js返回并作出应答
          String callFun = message.message; 
          String data = "收到消息调用了";
          String script = "$callFun($data)";
          controller.runJavaScript('callFlutterFunctionBack("JS Flutter222: ");');
        })*/
      },
    );
    controller.addJavaScriptChannel(
      "JsObj2",
      onMessageReceived: (JavaScriptMessage message) => {
        nextSubPageTwo()
      },
    );
    // ..loadHtmlString("<a href=&#34;/frontend&#34;>打开前端页面</a>")
    //controller.loadHtmlString(htmlString);
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    contextRef = context;
    return Scaffold(
      appBar: AppBar(title: const Text("WebPage")),
      body: Column(
        children: [
          /*ElevatedButton(
            onPressed: () => {
              // 执行JavaScript函数
              controller.runJavaScript("runJsOnly()"),
            },
            child: const Text('runJavaScript'),
          ),
          ElevatedButton(
            onPressed: () => {
              // 执行JavaScript函数
              controller.runJavaScript('JsObj.postMessage("JS Flutter222: ");'),
            },
            child: const Text('runJavaScript222'),
          ),
          ElevatedButton(
            onPressed: () => {
              _runJsWithResult(),
            },
            child: const Text('runJavaScriptReturningResult'),
          ),
          Text(message),*/
          Expanded(
            child: WebViewWidget(controller: controller),
          ),
        ],
      ),
    );
  }


  _runJsWithResult() async {
    // 执行JavaScript函数，并获取返回值
    var result =
        await controller.runJavaScriptReturningResult("runJsWithResult()");
    setState(() {
      message = result.toString();
    });
  }

  _loadHtmlFromAssets() async {
    String fileHtmlContent = await rootBundle.loadString(filePath);
    print("fileHtmlContent:" + fileHtmlContent);
    controller.loadHtmlString(fileHtmlContent);
  }

   Future<void> nextSubPage() async {
     Navigator.push(
       contextRef,
       MaterialPageRoute(builder: (context) => const SubWebPage(url: "https://m.hnair.com",)),
     );
   }

   Future<void> nextSubPageTwo() async {
     Navigator.push(
       contextRef,
       MaterialPageRoute(builder: (context) => const SubWebPageTwo()),
     );
   }

}